<?php
namespace app\test\controller;
use think\Controller;
use app\test\model\admin;
use think\Request;

class login extends Controller{

    //用户注册
    public function register()
    {
        if(Request()->isPost()){
            $post = input('post.');
            $file = request()->file('files');
            if (empty($file)) {
                $this->error('请选择上传文件');
            }
            if($file){
                $info = $file->move( ROOT_PATH . 'public' . DS . 'uploads');
                $photo = 'uploads\\'.$info->getSaveName();
//                echo '<pre>';
//                print_r($file);
//                print_r($info);
//                print_r($photo);
//                die;
            }

            $check = $this->validate($post, 'Admin');
            if(true !== $check) $this->error($check);

            $data = [
                'username' => $post['username'],
                'password' => md5($post['password']),
                'email' => $post['email'],
                'create_time' => time(),
                'photo' => $photo,
            ];
            $res = admin::insert($data);
            if(!$res){
                $this->error('注册失败！');
            } else {
                $this->success('注册成功！', 'login');
            }
        }
        return $this->fetch();
    }

    //用户登录
    public function login()
    {
        if(Request()->isPost()){
            $post = input('post.');
            //表单验证
            $check = $this->validate($post, 'Admin.login');
            if(true !== $check) $this->error($check);
            //用户账号密码校验
            $res = admin::where('username', $post['username'])->find();
            if($res){
                if($res['password'] === md5($post['password'])){
                    session('username', $res);
                } else {
                    $this->error('账号密码错误！');
                }
            } else {
                $this->error('用户不存！');
            }
            //验证码校验
            if(captcha_check($post['captcha'])){
                $this->success('登录成功！', '/test/index/index');
            } else {
                $this->error('验证码错误！');
            }
        }
        return $this->fetch();
    }

    //用户退出
    public function logout()
    {
        session(null);
        $this->success('退出登录成功！', 'login');
    }

}